﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace BluSteamServer.Model.TransactionImplementation
{
    public class ChangePasswordTransaction : Transaction
    {
        private readonly string _username;
        private readonly string _currentPassword;
        private readonly string _newPassword;

        private bool _validated;

        public ChangePasswordTransaction(string username, string currentPassword, string newPassword)
        {
            _username = username;
            _currentPassword = currentPassword;
            _newPassword = newPassword;

            _validated = false;
        }

        public void Validate()
        {
            // search for user requesting to change password
            //User user = null;
            //using (var context = new BluSteamEntities.EntityModelContainer())
            //{
            //    var query = from u in context.Users where u.Username == _username select u;
            //    user = query.FirstOrDefault();
            //}

            Dictionary<string, object> user = null;

            // username incorrect or user not yet registered
            if (user == null)
            {
                ConnectionManager.Instance.RemoveConnection(_username);
                string message = string.Format("$CP2011~{0}~RESPONSE~INCORRECT_USERNAME", _username);
                Network.Send(_username, message);
                return;
            }

            // user password is incorrect
            if (user["password"] as string != _currentPassword)
            {
                ConnectionManager.Instance.RemoveConnection(_username);
                string message = string.Format("$CP2011~{0}~RESPONSE~INCORRECT_PASSWORD", _username);
                Network.Send(_username, message);
                return;
            }

            _validated = true;
        }

        public void Execute()
        {
            if (_validated)
            {
                //using (var context = new BluSteamEntities.EntityModelContainer())
                //{
                //    var user = context.Users.First(u => u.Username == _username);
                //    user.Password = _newPassword;
                //    context.SaveChanges();
                //}

                string message = string.Format("$CP2011~{0}~RESPONSE~PASSWORD_CHANGED", _username);
                Network.Send(_username, message);
            }
        }
    }
}
